<template>
  <div class="lesson-page">
    <!-- 顶部导航 -->
    <van-nav-bar title="课时预约" fixed placeholder/>

    <!-- 筛选面板 -->
    <filter-panel
        v-model:courseTypeId="filter.courseTypeId"
        v-model:licenseTypeId="filter.licenseTypeId"
        @change="handleFilterChange"
    />

    <!-- 时间选项卡 -->
    <time-tabs
        :active="activeTab"
        @change="handleTabChange"
    />

    <!-- 课时列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
      >
        <lesson-card
            v-for="lesson in lessons"
            :key="lesson.id"
            :lesson="lesson"
            @reserved="handleReserve"
        />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue'
import {useRouter} from 'vue-router'
import {Toast} from 'vant'
import FilterPanel from './components/FilterPanel.vue'
import TimeTabs from './components/TimeTabs.vue'
import LessonCard from './components/LessonCard.vue'
import {pageLessonAPI, reserveLessonAPI} from '@/api/lesson'
import type {API} from "@/type/type";
import {showConfirmDialog} from 'vant';
import {showSuccessToast} from 'vant';
import DateUtil from "@/utils/DateUtils";

const router = useRouter()

// 筛选条件
const filter = reactive({
  courseTypeId: '',
  licenseTypeId: '',
  dateRange: [] as string[]
})
// 列表数据
const lessons = ref<API.ILesson[]>([])
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const activeTab = ref('all')
const pageParams = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 加载数据
const loadData = async (reset = false) => {
  try {
    if (reset) {
      pageParams.page = 1
      lessons.value = []
      finished.value = false
    }
    loading.value = true
    const params = {
      ...filter,
      page: pageParams.page,
      size: pageParams.size,
    }
    const {data} = await pageLessonAPI(params)
    if (reset) {
      lessons.value = data.data
    } else {
      lessons.value = [...lessons.value, ...data.data]
    }

    pageParams.total = data.total
    if (lessons.value.length >= pageParams.total) {
      finished.value = true
    } else {
      pageParams.page++
    }
  } catch (error) {
    Toast.fail('加载失败')
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 下拉刷新
const onRefresh = () => {
  refreshing.value = true
  loadData(true)
}

// 上拉加载
const onLoad = () => {
  loadData()
}

// 切换时间tab
const handleTabChange = (tab: string) => {
  activeTab.value = tab
  // 根据tab设置不同的时间范围
  const today = DateUtil.formatCustom(new Date(), 'YYYY-MM-dd')
  if (tab === 'today') {
    filter.dateRange = [today, today]
  } else if (tab === 'week') {
    const nextWeek = new Date()
    nextWeek.setDate(nextWeek.getDate() + 7)
    filter.dateRange = [today, nextWeek.toISOString().split('T')[0]]
  } else {
    filter.dateRange = []
  }
  loadData(true)
}

const handleFilterChange = () => {
  loadData(true)
}

const handleReserve = async (lesson: API.ILesson) => {
  showConfirmDialog({
    title: '确认预约',
    message: `确认预约该课时吗？课程驾照类型为${lesson.licenseTypeName}(${lesson.licenseTypeCode},学习科目为${lesson.courseSubjectName})`,
  }).then(async () => {
    const {data} = await reserveLessonAPI(lesson.id)
    if (data) {
      showSuccessToast('预约成功')
      // handleViewDetail(lesson)
      // 刷新
      loadData(true)
    }
  })
}

// 查看详情
const handleViewDetail = (lesson: API.ILesson) => {
  router.push(`/lesson/detail/${lesson.id}`)
}

// 首次加载数据
onMounted(() => {
  loadData(true)
})
</script>

<style lang="less" module>
.lesson-page {
  padding-bottom: 50px;

  :global {
    .van-nav-bar {
      background-color: #1989fa;
      color: white;

      .van-nav-bar__title {
        color: white;
      }
    }
  }
}
</style>
